package com.example.image.demos.service.impl;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.internal.OSSHeaders;
import com.aliyun.oss.model.*;
import com.example.image.demos.config.QiNiuConfig;
import com.example.image.demos.dto.ImageDto;
import com.example.image.demos.entity.User;
import com.example.image.demos.mapper.IUserDao;
import com.example.image.demos.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.image.demos.util.UUidUtil;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.*;
import com.qiniu.storage.model.DefaultPutRet;

import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ts
 * @since 2024-11-18
 */
@Service
//文件上传oss
public class UserServiceImpl extends ServiceImpl<IUserDao, User> implements IUserService {
    @Override
    public boolean uploadOSS(MultipartFile file) throws IOException {
        String fileName = file.getName();
        // Endpoint以华东（北京）为例，其它Region请按实际情况填写。
        String endpoint = "https://oss-cn-beijing.aliyuncs.com";
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = "LTAI5tE7DSEwERdkwsPsYshD";
        String accessKeySecret = "9gxz5oLiTbMDkxPngzhlELdCurFkiC";
        // 填写Bucket名称，例如examplebucket。
        String bucketName = "sskzs";
        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
        String originalFilename = file.getOriginalFilename();
        //JDK8的日期格式
        LocalDateTime time = LocalDateTime.now();
        DateTimeFormatter dft = DateTimeFormatter.ofPattern("yyyy/MM/dd");
        String folder = dft.format(time);
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        //在OSS上bucket下的文件名
        //image年份+月份+日期+文件名
        String uploadFileName = "image" + folder + "/" +fileName + extension;
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, uploadFileName, file.getInputStream());
            // 如果需要上传时设置存储类型和访问权限，请参考以下示例代码。
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
            metadata.setObjectAcl(CannedAccessControlList.PublicRead);
            putObjectRequest.setMetadata(metadata);
            // 上传文件
            ossClient.putObject(putObjectRequest);
            //获取路径
            URL url2 = ossClient.generatePresignedUrl(bucketName, uploadFileName,new Date());
            String path = url2.getPath();
            String url=url2.getProtocol()+"://"+url2.getHost()+"/"+path;
            System.out.println("url = " + url);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
                return true;
            }
        }
        return false;
    }
//上传文件到qi
    @Autowired
    private QiNiuConfig qiNiuConfig;
    private static String cdn="http://snacdlq4f.hd-bkt.clouddn.com";
    @Override
    public String uploadQi(MultipartFile file, ImageDto imageDto) throws IOException {
        //根据上传信息获取文件名字
        String fileName = file.getOriginalFilename();//用户输入名字
        int dotIndex = fileName.lastIndexOf('.');
        String extension = fileName.substring(dotIndex );//extension后缀
        String imageName = imageDto.getImageName()+UUidUtil.getUUid()+extension;//七牛云名字，imagdto获取的用户取得名字
        String imageTag = imageDto.getImageDetail();//描述
        //配置
        Configuration cfg = new Configuration(Region.region0());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        //...生成上传凭证，然后准备上传
        String accessKey = qiNiuConfig.getAccessKey();
        String secretKey = qiNiuConfig.getSecretKey();
        String bucket = qiNiuConfig.getBucket();
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = imageName;
        String url=cdn+"/"+imageDto.getImageName()+extension;
        System.out.println("url = " + url);
        try {
            byte[] uploadBytes = "hello qiniu cloud".getBytes("utf-8");//key为null用，一般用不上，懒得加判断
            ByteArrayInputStream byteInputStream=new ByteArrayInputStream(file.getBytes());
            Auth auth = Auth.create(accessKey, secretKey);
            long expireInSeconds = 3600; // 1小时，单位:秒
            long expire = System.currentTimeMillis() / 1000 + expireInSeconds;

            String upToken = auth.uploadToken(bucket);
            try {
                Response response = uploadManager.put(byteInputStream,key,upToken,null, null);
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                System.out.println(putRet.key);
                System.out.println(putRet.hash);
            } catch (QiniuException ex) {
                ex.printStackTrace();
                if (ex.response != null) {
                    System.err.println(ex.response);
                    try {
                        String body = ex.response.toString();
                        System.err.println(body);
                    } catch (Exception ignored) {
                    }
                }
            }
        } catch (UnsupportedEncodingException ex) {
            //ignore
        }
        return url;
    }
}

